<template>
  <view class="balance-bg">
    <!-- 顶部余额卡片 -->
    <view class="balance-card-simple">
      <view class="balance-label-row">
        <text class="balance-label">当前余额</text>
      </view>
      <text class="balance-value">¥{{ balance }}</text>
    </view>

    <!-- 充值金额选项宫格 -->
    <view class="amount-grid">
      <view v-for="item in quickAmounts" :key="item" :class="['amount-item', selectedAmount == item ? 'active' : '']" @click="selectAmount(item)">
        <text class="amount-main">{{ item }}元</text>
        <text class="amount-desc">售价{{ item.toFixed(2) }}元</text>
      </view>
    </view>

    <!-- 自定义金额输入 -->
    <view class="input-group-simple">
      <input class="amount-input-simple" v-model="rechargeAmount" type="number" placeholder="自定义金额" @focus="clearSelectedAmount" />
    </view>

    <!-- 充值按钮 -->
    <button class="recharge-btn-main" @click="handleRecharge('wechat')">微信充值</button>
    <button class="recharge-btn-main alipay" @click="handleRecharge('alipay')">支付宝充值</button>

    <!-- 优惠说明卡片 -->
    <view class="promo-card">
      <image src="/static/icons/balance.svg" class="promo-icon" />
      <text class="promo-text">充值1元送1积分，积分可用于优惠券兑换</text>
    </view>

    <!-- 支付宝二维码弹窗 -->
    <view v-if="showAlipayQrCode" class="qr-code-modal-simple">
      <view class="qr-code-content-simple">
        <view class="qr-code-header-simple">
          <text class="title">支付宝充值</text>
          <text class="close" @click="closeQrCode">×</text>
        </view>
        <view class="qr-code-body-simple">
          <image class="qr-code-img" :src="alipayQrCode" mode="aspectFit" />
          <text class="amount">¥{{ rechargeAmount }}</text>
          <text class="tip">请使用支付宝扫码支付</text>
          <text class="points-tip">充值后将获得{{ rechargeAmount }}积分</text>
          <button class="save-qr-btn" @click="saveQrCode">保存二维码到相册</button>
        </view>
        <view class="qr-code-footer-simple">
          <button class="check-payment-btn" @click="checkPaymentStatus()">已完成支付</button>
        </view>
      </view>
    </view>

    <!-- 积分规则底部说明 -->
    <view class="points-rule-bottom">
      <text>积分可用于兑换优惠券，更多福利敬请期待。</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { createAliPay, createWxPay, queryAliPayStatus, queryWxPayStatus } from '@/api/payment';
import { getUserAccount, updateUserBalance } from '@/api/user';
import Loading from '@/components/Loading.vue';

const balance = ref(0.00);
const rechargeAmount = ref('');
const showAlipayQrCode = ref(false);
const alipayQrCode = ref('');
const orderNo1 = ref('');
const isLoading = ref(false);
const quickAmounts = [30, 50, 100, 200, 300, 500];
const selectedAmount = ref<number|null>(null);

const selectAmount = (amount:number) => {
  selectedAmount.value = amount;
  rechargeAmount.value = amount.toString();
};
const clearSelectedAmount = () => {
  selectedAmount.value = null;
};

const fetchBalance = async () => {
  const userInfo = uni.getStorageSync('userInfo');
  if (userInfo && userInfo.id) {
    const res = await getUserAccount(userInfo.id);
    if (res && res.data && typeof res.data.balance !== 'undefined') {
      balance.value = res.data.balance;
    }
  }
};

onMounted(() => {
  fetchBalance();
});

const handleRecharge = async (type: 'wechat' | 'alipay') => {
  isLoading.value = true;
  const amount = Number(rechargeAmount.value);
  if (!amount || amount <= 0) {
    uni.showToast({ title: '请输入正确的充值金额', icon: 'none' });
    isLoading.value = false;
    return;
  }
  const userInfo = uni.getStorageSync('userInfo');
  if (!userInfo || !userInfo.id) {
    uni.showToast({ title: '请先登录', icon: 'none' });
    isLoading.value = false;
    return;
  }
  if (type === 'alipay') {
    orderNo1.value = `RECHARGE${Date.now()}`;
    const params = {
      orderNo: orderNo1.value,
      payMethod: 'alipay',
      amount,
      userId: userInfo.id,
      orderId: null,
      type: '充值'
    };
    const res = await createAliPay(params);
    if (res.code === 200) {
      isLoading.value = false;
      const qrCodeData = res.data;
      if (typeof qrCodeData === 'string') {
        alipayQrCode.value = qrCodeData;
      } else if (qrCodeData && qrCodeData.qrCode) {
        alipayQrCode.value = qrCodeData.qrCode;
      } else {
        uni.showToast({ title: '获取二维码失败', icon: 'none' });
        return;
      }
      showAlipayQrCode.value = true;
    } else {
      uni.showToast({ title: res.msg || '支付宝充值失败', icon: 'none' });
    }
  } else if (type === 'wechat') {
    isLoading.value = false;
    orderNo1.value = `RECHARGE${Date.now()}`;
    const params = {
      orderNo: orderNo1.value,
      userId: userInfo.id,
      orderId: null,
      paymentType: 1,
      paymentAmount: amount,
      type: '充值'
    };
    const res = await createWxPay(params);
    if (res.code === 200 && res.data && res.data.payParams) {
      uni.requestPayment({
        provider: 'wxpay',
        timeStamp: res.data.payParams.timeStamp,
        nonceStr: res.data.payParams.nonceStr,
        package: res.data.payParams.package,
        signType: res.data.payParams.signType,
        paySign: res.data.payParams.paySign,
        success: async () => {
          queryWxPayStatus(res.data.orderNo,"充值").then(async (res:any) => {
                if (res.code === 200 && res.data.status === 2) {
                uni.showToast({ title: '充值成功', icon: 'success' });
                const newBalance = Number(balance.value) + Number(amount);
                await updateUserBalance(userInfo.id, newBalance);
                fetchBalance();
                } else {
                  uni.showToast({ title: '支付状态查询失败', icon: 'none' });
                }
              }).catch(err => {
                uni.showToast({ title: '支付查询失败', icon: 'none' });
              });
        },
        fail: (err) => {
          uni.showToast({ title: '微信充值失败', icon: 'none' });
        }
      });
    } else {
      uni.showToast({ title: res.msg || '微信充值失败', icon: 'none' });
    }
  }
};

const closeQrCode = () => {
  showAlipayQrCode.value = false;
  alipayQrCode.value = '';
};

const saveQrCode = () => {
  if (!alipayQrCode.value) {
    uni.showToast({ title: '二维码未生成', icon: 'none' });
    return;
  }
  const qrCodeData = alipayQrCode.value;
  uni.getSetting({
    success: (res) => {
      if (!res.authSetting['scope.writePhotosAlbum']) {
        uni.authorize({
          scope: 'scope.writePhotosAlbum',
          success: () => {
            saveBase64ToAlbum();
          },
          fail: () => {
            uni.showModal({
              title: '提示',
              content: '需要相册权限才能保存二维码，请在设置中开启',
              showCancel: false,
              confirmText: '知道了'
            });
          }
        });
      } else {
        saveBase64ToAlbum();
      }
    }
  });
};

const saveBase64ToAlbum = () => {
  uni.showLoading({ title: '保存中...' });
  const qrCodeData = alipayQrCode.value;
  const base64Data = qrCodeData.replace(/^data:image\/\w+;base64,/, '');
  const arrayBuffer = uni.base64ToArrayBuffer(base64Data);
  const tempFilePath = `${uni.env.USER_DATA_PATH || wx.env.USER_DATA_PATH}/qrcode_${Date.now()}.png`;
  uni.getFileSystemManager().writeFile({
    filePath: tempFilePath,
    data: arrayBuffer,
    encoding: 'binary',
    success: () => {
      uni.saveImageToPhotosAlbum({
        filePath: tempFilePath,
        success: () => {
          uni.hideLoading();
          uni.showToast({ 
            title: '二维码已保存到相册', 
            icon: 'success',
            duration: 2000
          });
          uni.getFileSystemManager().unlink({
            filePath: tempFilePath,
            success: () => {},
            fail: (err) => {}
          });
        },
        fail: (err) => {
          uni.hideLoading();
          uni.showToast({ 
            title: '保存失败，请重试', 
            icon: 'none' 
          });
        }
      });
    },
    fail: (err) => {
      uni.hideLoading();
      uni.showToast({ 
        title: '保存失败，请重试', 
        icon: 'none' 
      });
    }
  });
};

const checkPaymentStatus = async () => {
  const userInfo = uni.getStorageSync('userInfo');
  const amount = Number(rechargeAmount.value);
  if (userInfo && userInfo.id && amount > 0) {
    try {
      const res = await queryAliPayStatus(orderNo1.value,"充值");
      if (res.code === 200) {
        const status = res.data;
        if (status == 'PAID') {
          const newBalance = Number(balance.value) + Number(amount);
          await updateUserBalance(userInfo.id, newBalance);
          fetchBalance();
          uni.showToast({ title: '充值成功', icon: 'success' });
        } else if (status === 'CLOSED') {
          uni.showToast({ title: '订单已关闭', icon: 'none' });
        } else {
          uni.showToast({ title: '支付未完成', icon: 'none' });
        }
      }
    } catch (e) {
      uni.showToast({ title: '查询支付状态失败', icon: 'none' });
    }
  }
  closeQrCode();
};
</script>

<style scoped>
.balance-bg {
  min-height: 100vh;
  background: #f7f7f7;
  padding: 32rpx 0 0 0;
}
.balance-card-simple {
  background: #fff;
  border-radius: 24rpx;
  box-shadow: 0 2px 12px rgba(0,0,0,0.06);
  margin: 0 24rpx 32rpx 24rpx;
  padding: 36rpx 0 24rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.balance-label-row {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  padding-left: 36rpx;
  margin-bottom: 8rpx;
}
.balance-label {
  font-size: 30rpx;
  color: #888;
}
.balance-value {
  font-size: 60rpx;
  color: #222;
  font-weight: bold;
  margin-top: 8rpx;
}
.amount-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 18rpx 0;
  margin: 0 24rpx 18rpx 24rpx;
}
.amount-item {
  width: 44%;
  margin: 0 2.5% 18rpx 2.5%;
  background: #fff;
  border-radius: 18rpx;
  border: 1px solid #e5e5e5;
  box-shadow: 0 1px 4px rgba(0,0,0,0.03);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 18rpx 0 10rpx 0;
  cursor: pointer;
  transition: border 0.2s, box-shadow 0.2s;
}
.amount-item.active {
  border: 2px solid #1677ff;
  box-shadow: 0 2px 8px #1677ff22;
}
.amount-main {
  font-size: 32rpx;
  color: #222;
  font-weight: 600;
}
.amount-desc {
  font-size: 22rpx;
  color: #888;
  margin-top: 6rpx;
}
.input-group-simple {
  margin: 0 24rpx 18rpx 24rpx;
}
.amount-input-simple {
  width: 100%;
  height: 80rpx;
  font-size: 32rpx;
  border-radius: 12rpx;
  border: 1px solid #ddd;
  padding: 0 20rpx;
  background: #fff;
  margin-bottom: 10rpx;
}
.recharge-btn-main {
  width: 90%;
  height: 88rpx;
  font-size: 32rpx;
  border-radius: 44rpx;
  margin: 18rpx 5% 0 5%;
  background: #1677ff;
  color: #fff;
  border: none;
  box-shadow: 0 2px 8px #1677ff22;
}
.recharge-btn-main.alipay {
  background: #00b8a9;
}
.promo-card {
  margin: 32rpx 24rpx 0 24rpx;
  background: #fff7e6;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  padding: 18rpx 24rpx;
  box-shadow: 0 1px 4px #ffe7ba44;
}
.promo-icon {
  width: 36rpx;
  height: 36rpx;
  margin-right: 16rpx;
}
.promo-text {
  font-size: 26rpx;
  color: #ff9800;
}
.qr-code-modal-simple {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}
.qr-code-content-simple {
  width: 80%;
  max-width: 600rpx;
  background-color: #fff;
  border-radius: 20rpx;
  overflow: hidden;
}
.qr-code-header-simple {
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
}
.qr-code-header-simple .title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}
.qr-code-header-simple .close {
  font-size: 40rpx;
  color: #999;
  padding: 0 20rpx;
}
.qr-code-body-simple {
  padding: 40rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.qr-code-img {
  width: 400rpx;
  height: 400rpx;
  margin-bottom: 30rpx;
}
.amount {
  font-size: 40rpx;
  font-weight: 600;
  color: #ff4d4f;
  margin-bottom: 20rpx;
}
.tip {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 15rpx;
}
.points-tip {
  font-size: 26rpx;
  color: #ff6b6b;
  background: #fff5f5;
  padding: 10rpx 20rpx;
  border-radius: 20rpx;
  border: 1px solid #ffccc7;
  margin-bottom: 20rpx;
}
.save-qr-btn {
  width: 100%;
  height: 70rpx;
  line-height: 70rpx;
  background: linear-gradient(135deg, #4CAF50, #45a049);
  color: #fff;
  font-size: 28rpx;
  border-radius: 35rpx;
  border: none;
  margin-top: 20rpx;
  box-shadow: 0 2px 8px rgba(76, 175, 80, 0.3);
}
.qr-code-footer-simple {
  padding: 30rpx;
  border-top: 1px solid #f0f0f0;
}
.check-payment-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background: linear-gradient(135deg, #ff6b6b, #ff4d4f);
  color: #fff;
  font-size: 32rpx;
  border-radius: 40rpx;
  border: none;
}
.points-rule-bottom {
  margin: 48rpx 0 0 0;
  text-align: center;
  color: #bbb;
  font-size: 24rpx;
}
</style> 